import json
import requests as rq
import time

def main():
    with open('all_gynecological.txt','r') as fr:
        all = fr.read().split('\n')

    # print(all)
    line = 0
    allHospitals = []
    while line < len(all):
        thisHospital = []
        print(line, len(all))
        if all[line] == '空降兵军医院':
            itemsThis = 23
        else:
            itemsThis = 23
        for i in range(0, itemsThis):
            thisHospital.append(all[line])
            line += 1
            if line >= len(all):
                break

        # print(thisHospital)
        allHospitals.append(thisHospital)

    cfmName = []
    cfmAddr = []

    allC = []
    for a in range(0, len(allHospitals)):
        time.sleep(0.2)
        print(a, len(allHospitals))
        thisH = allHospitals[a]
        if len(thisH) == 15:
            continue
        thisC = {}
        # for i in range(0, len(thisH)):
        #     print(i, thisH[i])

        if thisH[0].find('（') != -1:
            truncName = thisH[0][:thisH[0].find('（')]
        else:
            truncName = thisH[0]
        print(thisH[0], truncName, len(thisH))
        if len(thisH) == 22:
            thisC['validity'] = thisH[1]

            avail5 = avail(thisH[5])
            avail7 = avail(thisH[7])
            avail9 = avail(thisH[9])
            avail11 = avail(thisH[11])
            avail13 = avail(thisH[13])
            avail15 = avail(thisH[15])
            avail17 = avail(thisH[17])

            thisC['normalPregnant'] = avail5
            thisC['suspectConfirmedPregnant'] = avail7
            thisC['normalPregnancyCheck'] = avail9
            thisC['ultraB'] = avail11
            thisC['deformityExclusion'] = avail13
            thisC['delivery'] = avail15
            thisC['naCheck'] = avail17

            thisC['normalPregnant2'] = thisH[5].replace(' ','')
            thisC['suspectConfirmedPregnant2'] = thisH[7].replace(' ','')
            thisC['normalPregnancyCheck2'] = thisH[9].replace(' ','')
            thisC['ultraB2'] = thisH[11].replace(' ','')
            thisC['deformityExclusion2'] = thisH[13].replace(' ','')
            thisC['delivery2'] = thisH[15].replace(' ','')
            thisC['naCheck2'] = thisH[17].replace(' ','')

            thisC['info'] = ''
            thisAddr = thisH[20].replace(' ','')
        else:
            thisC['validity'] = thisH[1]

            avail5 = avail(thisH[5])
            avail7 = avail(thisH[7])
            avail9 = avail(thisH[9])
            avail11 = avail(thisH[11])
            avail13 = avail(thisH[13])
            avail15 = avail(thisH[15])
            avail17 = avail(thisH[17])

            thisC['normalPregnant'] = avail5
            thisC['suspectConfirmedPregnant'] = avail7
            thisC['normalPregnancyCheck'] = avail9
            thisC['ultraB'] = avail11
            thisC['deformityExclusion'] = avail13
            thisC['delivery'] = avail15
            thisC['naCheck'] = avail17

            thisC['normalPregnant2'] = thisH[5].replace(' ','')
            thisC['suspectConfirmedPregnant2'] = thisH[7].replace(' ','')
            thisC['normalPregnancyCheck2'] = thisH[9].replace(' ','')
            thisC['ultraB2'] = thisH[11].replace(' ','')
            thisC['deformityExclusion2'] = thisH[13].replace(' ','')
            thisC['delivery2'] = thisH[15].replace(' ','')
            thisC['naCheck2'] = thisH[17].replace(' ','')

            thisC['info'] = thisH[21].replace(' ','')
            thisAddr = thisH[21].replace(' ','')

        # url = 'https://restapi.amap.com/v3/place/text?key=de1fb1729e2e4f6fb20d2e6ea3ac8e27' \
        #   '&keywords=' + thisAddr + '&types=090100|090200|090300|090400|090500&city=武汉市&children=0&offset=1&page=1&extensions=all'
        url = 'https://restapi.amap.com/v3/place/text?key=de1fb1729e2e4f6fb20d2e6ea3ac8e27' \
                  '&keywords=' + truncName + '&types=090100|090200|090300|090400|090500&city=武汉市&children=0&offset=1&page=1&extensions=all'

            # 'http://apis.map.qq.com/ws/place/v1/search?boundary=region(武汉,0)&page_size=1&page_index=1' \
            #   '&keyword=' + truncName + '&orderby=_distance&key=NL7BZ-4EQCF-B2CJ4-NGQN5-LETB7-DYFPM'
        print(url)
        response = rq.get(url)
        result = response.json()
        usingTMap = False
        if thisH[0] == '武汉广发肿瘤医院' or a in [3,5,13,15,20,28,31,39,40,46,48,57,69,74]:
            if a == 57 or a == 28:
                thisKey = thisH[0]
            else:
                thisKey = truncName
            tencentUrl = 'http://apis.map.qq.com/ws/place/v1/search?boundary=region(武汉,0)&page_size=1&page_index=1' \
                         '&keyword=' + thisKey + '&orderby=_distance&key=NL7BZ-4EQCF-B2CJ4-NGQN5-LETB7-DYFPM'
            response = rq.get(tencentUrl)
            result = response.json()
            usingTMap = True
        print(result)

        if usingTMap == False:
            for k, v in result['pois'][0].items():
                if v == []:
                    result['pois'][0][k] = ''

            if len(result['pois']) == 0:
                url = 'https://restapi.amap.com/v3/place/text?key=de1fb1729e2e4f6fb20d2e6ea3ac8e27' \
                      '&keywords=' + thisAddr + '&types=090100|090200|090300|090400|090500&city=武汉市&children=0&offset=1&page=1&extensions=all'
                response = rq.get(url)
                result = response.json()

                if len(result['pois']) == 0:
                    gaodeURL = 'http://apis.map.qq.com/ws/place/v1/search?boundary=region(武汉,0)&page_size=1&page_index=1' \
                               '&keyword=' + truncName + '&orderby=_distance&key=NL7BZ-4EQCF-B2CJ4-NGQN5-LETB7-DYFPM'
                    response = rq.get(gaodeURL)
                    result = response.json()
                    usingTMap = True
        if usingTMap:
            print(result)
            fmt_addr = result['data'][0]['address']
            fmt_name = result['data'][0]['title']
            fmt_type1 = result['data'][0]['category'].split(':')[1]
            try:
                fmt_type2 = result['data'][0]['category'].split(':')[2]
            except:
                fmt_type2 = ''
            fmt_alias = ''
            fmt_district = result['data'][0]['ad_info']['district']
            fmt_lng = result['data'][0]['location']['lng']
            fmt_lat = result['data'][0]['location']['lat']
            fmt_tel = result['data'][0]['tel']
        # if notFound:
        #     print('NOT FOUND', thisH)
        #     fmt_addr = thisAddr
        #     fmt_name = thisH[0]
        #     fmt_type1 = ''
        #     fmt_type2 = ''
        #     fmt_alias = ''
        #     fmt_district = ''
        #     fmt_lng = '-999'
        #     fmt_lat = '-999'
        #     fmt_tel = ''
        else:
            fmt_addr = result['pois'][0]['address']
            fmt_name = result['pois'][0]['name']
            fmt_type1 = result['pois'][0]['type'].split(';')[1]
            fmt_type2 = result['pois'][0]['type'].split(';')[2]
            fmt_alias = result['pois'][0]['alias'].replace('|', '；')
            fmt_district = result['pois'][0]['adname']
            fmt_lng = result['pois'][0]['location'].split(',')[0]
            fmt_lat = result['pois'][0]['location'].split(',')[1]
            fmt_tel = result['pois'][0]['tel'].replace(';', '；')

        cfmName.append(fmt_name + '=====' + thisH[0])
        cfmAddr.append(fmt_addr + '=====' + thisAddr)

        addInfo = {'hospitalName': fmt_name,
         'hospitalAlias': fmt_alias,
         'tel_GaodeMapAPI': fmt_tel,
         'district': fmt_district,
         'address': fmt_addr,
         'type1': fmt_type1,
         'type2': fmt_type2,
         'lng': float(fmt_lng),
         'lat': float(fmt_lat)
         }

        thisC.update(addInfo)
        allC.append(thisC)

    all = {'gynecologicalHospitals':[]}
    all['gynecologicalHospitals'] = [allC]

    with open('formattedGH0302.json','w') as fw:
        fw.write(json.dumps(all, ensure_ascii=False, separators=(',',':')))
    with open('cfm0302.csv','w') as fw:
        for i in range(0, len(cfmName)):
            fw.write(str(i) + '\n' + cfmName[i] + '\n' + cfmAddr[i] + '\n\n')

def avail(info):
    info = info.replace(' ','')
    print(info, info == '接收' or info == '可做')
    if ('不' in info):
        return -1
    elif info == '接收' or info == '可做':
        return 1
    else:
        return 0

if __name__ == '__main__':
    main()
